package ltd.dujiabao.orderservice.service;

import ltd.dujiabao.orderservice.dao.OrderRepository;
import ltd.dujiabao.orderservice.domain.dto.CreateOrderDto;
import ltd.dujiabao.common.event.CreateOrderEvent;
import ltd.dujiabao.orderservice.domain.entity.Order;
import ltd.dujiabao.orderservice.domain.enums.OrderStatus;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author Bowie Du
 * @date 2025/7/13 15:48
 */

@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductApi productApi;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Transactional(rollbackFor = Exception.class)
    public void createOrder(CreateOrderDto dto) {
        // 创建订单
        LocalDateTime now = LocalDateTime.now();
        Order order = new Order()
                .setUserId(dto.getUserId())
                .setProductId(dto.getProductId())
                .setQuantity(dto.getQuantity())
                .setStatus(OrderStatus.ORDER_CREATED.name())
                .setCreatedAt(now)
                .setUpdatedAt(now);
        order = orderRepository.save(order);

        // 计算金额
        BigDecimal price = productApi.getPriceById(dto.getProductId());
        BigDecimal amount = price.multiply(new BigDecimal(dto.getQuantity()));

        // 发布事件
        CreateOrderEvent event = CreateOrderEvent.builder()
                .orderId(order.getId())
                .userId(dto.getUserId())
                .quantity(dto.getQuantity())
                .productId(dto.getProductId())
                .amount(amount)
                .build();
        rabbitTemplate.convertAndSend("order.success.exchange", "", event);
    }
}
